NO_TAB = 0;
TWO_WHITE_SPACE_TAB = 2;
FOUR_WHITE_SPACE_TAB = 4;
EIGHT_WHITE_SPACE_TAB = 8;
var paramsDefinition = "";
var isLanguageCN = true; // false:EN

function selectLanguage() {
    var language = document.getElementById("language");
    var supportedPlatform = document.getElementById("supported_platform");
    var samples = document.getElementById("samples");
    var title_desc = document.getElementById("title_desc");
    var title_param = document.getElementById("title_param");
    var title_keyword_param = document.getElementById("title_keyword_param");
    var title_input = document.getElementById("title_input");
    var title_output = document.getElementById("title_output");
    var title_return = document.getElementById("title_return");
    var title_exception = document.getElementById("title_exception");
    var title_supported_platform = document.getElementById("title_supported_platform");
    var title_sample = document.getElementById("title_sample");
    if (language.options[0].select) {
        isLanguageCN = true;
    } else if (language.options[1].selected) {
        isLanguageCN = false;
    } else {
        isLanguageCN = true;
    }
    const languageSelect = document.getElementById('language');
    const writeTypeSelect = document.getElementById('writetype');

    if (languageSelect.value === 'cn') {
        writeTypeSelect.disabled = true; // 置灰并设为不可选
    } else {
        writeTypeSelect.disabled = false; // 启用并可选
    }

    // title_desc.innerHTML = isLanguageCN ? "API类型&名称&功能概述：" : "API Type & Name & Descriptions:";
    // title_param.innerHTML = isLanguageCN ? "参数：" : "Args:";
    // title_keyword_param.innerHTML = isLanguageCN ? "关键字参数：" : "Keyword Args:";
    // title_input.innerHTML = isLanguageCN ? "输入：" : "Inputs:";
    // title_output.innerHTML = isLanguageCN ? "输出：" : "Outputs:";
    // title_return.innerHTML = isLanguageCN ? "返回：" : "Returns:";
    // title_exception.innerHTML = isLanguageCN ? "异常：" : "Raises:";
    // title_supported_platform.innerHTML = isLanguageCN ? "支持平台：" : "Supported Platforms:";
    // title_sample.innerHTML = isLanguageCN ? "样例：" : "Examples:";
    // supportedPlatform.style.display = isLanguageCN ? 'none' : 'block';
    // samples.style.display = isLanguageCN ? 'none' : 'block';
    // document.getElementById("preview").value = "";
    // samplesEventInit();
}

function samplesEventInit() {
    var code = document.getElementById("code");

    code.onkeydown = function (event) {
        var userInput = event.key;

        if (userInput === "Enter") {
            var lines = code.value.split("\n");
            var newLines = "";
            for (var i = 0; i < lines.length; i++) {
                newLines += (i < lines.length - 1) ? (lines[i] + "\n") : (lines[i].length > 4 && lines[i].charAt(4) == ' ') ? lines[i].replace(">>> ", "... ") : lines[i];
            }
            code.value = newLines + "\n>>> ";

            event.preventDefault();
        }
    };

}

function selectWritetype() {
    const writeTypeSelect = document.getElementById('writetype');
    alert('选中的写入类型是: ' + writeTypeSelect.value);
}

// 页面加载时，初始化第二个下拉栏的状态
window.onload = function () {
    selectLanguage(); // 根据第一个下拉栏的初始值设置第二个下拉栏的状态
};

// function selectApiType() {
//     var mySelect = document.getElementById("apiType");   //定位id（获取select）
// var param = document.getElementById("param");
// var input = document.getElementById("input");
// var output = document.getElementById("output");
// var returns = document.getElementById("return");
// if (mySelect.options[0].selected) {  //注意index是从0开始的
//     param.style.display = 'block';
//     input.style.display = 'block';
//     output.style.display = 'block';
//     returns.style.display = 'none';
// } else if (mySelect.options[1].selected) {
//     param.style.display = 'block';
//     input.style.display = 'none';
//     output.style.display = 'none';
//     returns.style.display = 'block';
// } else {
//     param.style.display = 'block';
//     input.style.display = 'none';
//     output.style.display = 'none';
//     returns.style.display = 'block';
// }
// document.getElementById("preview").value = "";
// }

var claSample =
    `mindspore.ops.name
=====================

.. py:class:: mindspore.ops.name(default_input, dtype=None, init_with_data=True, *, abc)

    算子简介。 

    .. math::
        这是一个公式实例（请删除这行，需缩进四格再开始写公式，可选）

    某函数图（可选）：

    .. image:: 图片路径
        :align: center

    .. warning::
        这是一个warning，需缩进四格再写，可选。

    .. note::
        这是一个note，需缩进四格再写，可选。

    参数：
        - **参数1** (Tensor) – 参数1说明。
        - **参数2** (int, 可选) – 参数2说明。默认 ` + "``None``" + ` 。（有默认一定要加可选）
          还有说明请从这里开始写（首字与*符号对齐）。这是公式 :math:` + "`op(A) X = b`" + ` 。

          - **二级参数1** (int) – 二级参数1说明。（注意：二级参数需要和上面一级参数的“*”对齐。）

    关键字参数：
        - **abc** (bool, 可选) - 参数abc说明。 默认 ` + "``None``" + ` 。（有默认一定要加可选）

    输入（有输入就用输出，没输入就用返回）：
        - **输入1** (Tensor) - 输入1描述。
        - **输入2** (Tensor) - 输入2描述。

    返回：
        返回说明，可选。

    输出：
        - **输出1** (Tensor) - 输出1描述。
        - **输出2** (Tensor) - 输出2描述。

    异常：
        - **TypeError** – 异常描述1。
        - **ValueError** – 异常描述2。
    `;

var funSample =
    `mindspore.ops.name
=====================

.. py:function:: mindspore.ops.name(default_input, dtype=None, init_with_data=True, *, abc)

    算子简介。 

    .. math::
        这是一个公式实例（请删除这行，需缩进四格再开始写公式，可选）

    某函数图（可选）：

    .. image:: 图片路径
        :align: center

    .. warning::
        这是一个warning，需缩进四格再写，可选。

    .. note::
        这是一个note，需缩进四格再写，可选。

    参数：
        - **参数1** (Tensor) – 参数1说明。
        - **参数2** (int, 可选) – 参数2说明。默认 ` + "``None``" + ` 。（有默认一定要加可选）
          还有说明请从这里开始写（首字与*符号对齐）。这是公式 :math:` + "`op(A) X = b`" + ` 。

          - **二级参数1** (int) – 二级参数1说明。（注意：二级参数需要和上面一级参数的“*”对齐。）

    关键字参数：
        - **abc** (bool, 可选) - 参数abc说明。 默认 ` + "``None``" + ` 。（有默认一定要加可选）

    返回：
        返回说明，可选。

    异常：
        - **TypeError** – 异常描述1。
        - **ValueError** – 异常描述2。
    `;

var metSample1 =
    `mindspore.Tensor.name
=====================

.. py:method:: mindspore.Tensor.name(default_input, dtype=None, init_with_data=True, *, abc)

    算子简介。 

    .. math::
        这是一个公式实例（请删除这行，需缩进四格再开始写公式，可选）

    某函数图（可选）：

    .. image:: 图片路径
        :align: center

    .. warning::
        这是一个warning，需缩进四格再写，可选。

    .. note::
        这是一个note，需缩进四格再写，可选。

    参数：
        - **参数1** (Tensor) – 参数1说明。
        - **参数2** (int, 可选) – 参数2说明。默认 ` + "``None``" + ` 。（有默认一定要加可选）
          还有说明请从这里开始写（首字与*符号对齐）。这是公式 :math:` + "`op(A) X = b`" + ` 。

          - **二级参数1** (int) – 二级参数1说明。（注意：二级参数需要和上面一级参数的“*”对齐。）

    关键字参数：
        - **abc** (bool, 可选) - 参数abc说明。 默认 ` + "``None``" + ` 。（有默认一定要加可选）

    返回：
        返回说明，可选。

    异常：
        - **TypeError** – 异常描述1。
        - **ValueError** – 异常描述2。
    `;

var tensorSampler =
    `mindspore.Tensor.name
=======================

.. py:method:: mindspore.Tensor.name(dim, index)

    算子简介。

    .. math::
        这是一个公式实例（请删除这行，需缩进四格再开始写公式，可选）

    某函数图（可选）：

    .. image:: 图片路径
        :align: center

    .. warning::
        这是一个warning，需缩进四格再写，可选。

    .. note::
        这是一个note，需缩进四格再写，可选。

    参数：
        - **参数1** (Tensor) – 参数1说明。
        - **参数2** (int, 可选) – 参数2说明。默认 ` + "``None``" + ` 。（有默认一定要加可选）
          还有说明请从这里开始写（首字与*符号对齐）。这是公式 :math:` + "`op(A) X = b`" + ` 。

          - **二级参数1** (int) – 二级参数1说明。（注意：二级参数需要和上面一级参数的“*”对齐。）

    返回：
        返回说明，可选。

    异常：
        - **TypeError** – 异常描述1。
        - **ValueError** – 异常描述2。

    .. py:method:: mindspore.Tensor.name(input_indices, axis, batch_dims=0)
        :noindex:

    算子简介。

    .. math::
        这是一个公式实例（请删除这行，需缩进四格再开始写公式，可选）

    某函数图（可选）：

    .. image:: 图片路径
        :align: center

    .. warning::
        这是一个warning，需缩进四格再写，可选。

    .. note::
        这是一个note，需缩进四格再写，可选。

    参数：
        - **参数1** (Tensor) – 参数1说明。
        - **参数2** (int, 可选) – 参数2说明。默认 ` + "``None``" + ` 。（有默认一定要加可选）
          还有说明请从这里开始写（首字与*符号对齐）。这是公式 :math:` + "`op(A) X = b`" + ` 。

          - **二级参数1** (int) – 二级参数1说明。（注意：二级参数需要和上面一级参数的“*”对齐。）

    返回：
        返回说明，可选。

    异常：
        - **TypeError** – 异常描述1。
        - **ValueError** – 异常描述2。
    `;

var metSample2 =
    `mindspore.Tensor.abs
======================
    
.. py:method:: mindspore.Tensor.abs()
    
    详情请参考 :func:` + "`mindspore.ops.abs`" + `。
    或:func:` + "`mindspore.Tensor.solute` " + `的别名。
    `;

var metSample2p =
    `def abs(self)
    """
    For details, please refer to :func:` + "`mindspore.ops.abs`" + `。
    """
    `;

var claSampley =
    `name:
    description: |
        please describe 

        .. math::
            This is an example of a formula.

        f(x) Graph(optional)：

        .. image:: pic path
            :align: center

        .. warning::
            Warning description.

        Note:
            Note description. 

        Args:
            input_data (Tensor, optional): Input data of the tensor.
                describe more information.Default ` + "``None``" + `.This is a formula :math:` + "`op(A) X = b`" + ` .
            Arg2 (Type): Description.

                - Sub-argument1 or Value1 of Arg2: Description.

        Keyword Args:
            generator (:class:` + "`mindspore.Generator`" + `): a pseudorandom number generator.
        
        Inputs(有Inputs就用Outputs，没有Inputs用Returns):
            - **x** (Tensor) - The input of PReLU with data type of float16 or float32.
              describe more information.

        Returns:
            Type, description.
            more description.

        Outputs:
            Tensor, with the same shape as ` + "`input_data`" + `.

        Raises:
            TypeError: description.
                more description.
            ValueError: description.
        
        Supported Platforms:
            ` + "``Ascend``" + ` ` + "``GPU``" + ` ` + "``CPU``" + `

        (此段为说明，请删除此行，保持与前段仅空一行的距离。针对算子和Cell的注释，需要在Examples前添加Inputs、Outputs和Supported Platforms三项内容。)
        Examples:
            >>> description.
    `;

var claSamplep =
    `class Tensor(Cell or your args kwargs):
    r"""
    please describe

    .. math::
        This is an example of a formula.

    f(x) Graph(optional)：

    .. image:: pic path
        :align: center

    .. warning::
        Warning description.

    Note:
        Note description.

    Args:
        input_data (Tensor, optional): Input data of the tensor.
            describe more information.Default ` + "``None``" + `.This is a formula :math:` + "`op(A) X = b`" + ` .
        Arg2 (Type): Description.

            - Sub-argument1 or Value1 of Arg2: Description.
              describe more information.

    Keyword Args:
        generator (:class:` + "`mindspore.Generator`" + `): a pseudorandom number generator.

    Inputs(有Inputs就用Outputs，没有Inputs用Returns):
        - **x** (Tensor) - The input of PReLU with data type of float16 or float32.
          describe more information.

    Returns:
        Type, description.
        more description.

    Outputs:
        Tensor, with the same shape as ` + "`input_data`" + `.

    Raises:
        TypeError: description.
            more description.
        ValueError: description.

    Supported Platforms:
        ` + "``Ascend``" + ` ` + "``GPU``" + ` ` + "``CPU``" + `

    (此段为说明，请删除此行，保持与前段仅空一行的距离。针对算子和Cell的注释，需要在Examples前添加Inputs、Outputs和Supported Platforms三项内容。)
    Examples:
        >>> description.
    """
    `;

var funSamplep =
    `def name(input_data, Arg2, *, abc)
    r"""
    please describe

    .. math::
        This is an example of a formula.

    f(x) Graph(optional)：

    .. image:: pic path
        :align: center

    .. warning::
        Warning description.

    Note:
        Note description.

    Args:
        input_data (Tensor, optional): Input data of the tensor.
            describe more information.Default ` + "``None``" + `.This is a formula :math:` + "`op(A) X = b`" + ` .
        Arg2 (Type): Description.

            - Sub-argument1 or Value1 of Arg2: Description.
              describe more information.

    Keyword Args:
        abc (Tensor): a pseudorandom number generator.

    Returns:
        Type, description.
        more description.

    Raises:
        TypeError: description.
            more description.
        ValueError: description.

    Supported Platforms:
        ` + "``Ascend``" + ` ` + "``GPU``" + ` ` + "``CPU``" + `

    Examples:
        >>> description.
    """
    `;

var funSampley =
    `name:
    description: |
        please describe 

        .. math::
            This is an example of a formula.

        f(x) Graph(optional)：

        .. image:: pic path
            :align: center

        .. warning::
            Warning description.

        Note:
            Note description. 

        Args:
            input_data (Tensor, optional): Input data of the tensor.
                describe more information.Default ` + "``None``" + `.This is a formula :math:` + "`op(A) X = b`" + ` .
            Arg2 (Type): Description.

                - Sub-argument1 or Value1 of Arg2: Description.
                  describe more information.

        Keyword Args:
            abc (Tensor): a pseudorandom number generator.
        
        Returns:
            Type, description.
            more description.

        Raises:
            TypeError: description.
                more description.
            ValueError: description.
        
        Supported Platforms:
            ` + "``Ascend``" + ` ` + "``GPU``" + ` ` + "``CPU``" + `

        Examples:
            >>> description.
    `;

var tensorSampley = 
    `name:
    description: |
    name(input_data, Arg2) -> Tensor

    please describe

    .. math::
        This is an example of a formula.

    f(x) Graph(optional)：

    .. image:: pic path
        :align: center

    .. warning::
        Warning description.

    Note:
        Note description. 

    Args:
        input_data (Tensor, optional): Input data of the tensor.
            describe more information.Default ` + "``None``" + `.This is a formula :math:` + "`op(A) X = b`" + ` .
        Arg2 (Type): Description.

            - Sub-argument1 or Value1 of Arg2: Description.
                describe more information.

    Returns:
        Type, description.
        more description.

    Raises:
        TypeError: description.
            more description.
        ValueError: description.

    Supported Platforms:
        ` + "``Ascend``" + ` ` + "``GPU``" + ` ` + "``CPU``" + `

    Examples:
        >>> import mindspore
        >>> import numpy as np
        >>> from mindspore import Tensor
        >>> input = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
        >>> index = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
        >>> output = input.gather(1, index)
        >>> print(output)
        [[-0.1 -0.1]
        [0.5   0.5]]

    .. method:: Tensor.gather(input_data1, Arg3) -> Tensor
        :noindex:

    please describe.

    .. math::
        This is an example of a formula.

    f(x) Graph(optional)：

    .. image:: pic path
        :align: center

    .. warning::
        Warning description.

    Note:
        Note description. 

    Args:
        input_data1 (Tensor, optional): Input data of the tensor.
            describe more information.Default ` + "``None``" + `.This is a formula :math:` + "`op(A) X = b`" + ` .
        Arg3 (Type): Description.

            - Sub-argument1 or Value1 of Arg2: Description.
                describe more information.

    Returns:
        Type, description.
        more description.

    Raises:
        TypeError: description.
            more description.
        ValueError: description.

    Supported Platforms:
        ` + "``Ascend``" + ` ` + "``GPU``" + ` ` + "``CPU``" + `

    Examples:
        >>> import mindspore
        >>> import numpy as np
        >>> from mindspore import Tensor
        >>> # case1: input_indices is a Tensor with shape (5, ).
        >>> input_params = Tensor(np.array([1, 2, 3, 4, 5, 6, 7]), mindspore.float32)
        >>> input_indices = Tensor(np.array([0, 2, 4, 2, 6]), mindspore.int32)
        >>> axis = 0
        >>> output = input_params.gather(input_indices=input_indices, axis=axis)
        >>> print(output)
        [1. 3. 5. 3. 7.]
  `;
      
function addSample() {
    var mySelect = document.getElementById("apiType");
    var languageSelect = document.getElementById('language');
    var writeTypeSelect = document.getElementById("writetype");
    let language = languageSelect.value
    let writeType = writeTypeSelect.value
    if (mySelect.options[0].selected) {
        if (language === 'cn') {
            var textArea = document.getElementById("desc");
            textArea.value = claSample;
        }
        else if (language === 'en' && writeType === 'yaml') {
            var textArea = document.getElementById("desc");
            textArea.value = claSampley;
            console.log(textArea);
        } else if (language === 'en' && writeType === 'python') {
            var textArea = document.getElementById("desc");
            textArea.value = claSamplep;
        }
    }
    else if (mySelect.options[1].selected) {
        if (language === 'cn') {
            var textArea = document.getElementById("desc");
            textArea.value = funSample;
        }
        else if (language === 'en' && writeType === 'yaml') {
            var textArea = document.getElementById("desc");
            textArea.value = funSampley;
        } else if (language === 'en' && writeType === 'python') {
            var textArea = document.getElementById("desc");
            textArea.value = funSamplep;
        }
    }
    else if (mySelect.options[2].selected) {
        if (language === 'cn') {
            var textArea = document.getElementById("desc");
            textArea.value = metSample1;
        }
        else if (language === 'en' && writeType === 'yaml') {
            var textArea = document.getElementById("desc");
            textArea.value = '';
        } else if (language === 'en' && writeType === 'python') {
            var textArea = document.getElementById("desc");
            textArea.value = funSamplep;
        }
    }
    else if (mySelect.options[3].selected){
        if (language === 'cn') {
            var textArea = document.getElementById("desc");
            textArea.value = metSample2;
        }
        else if (language === 'en' && writeType === 'yaml') {
            var textArea = document.getElementById("desc");
            textArea.value = '';
        } else if (language === 'en' && writeType === 'python') {
            var textArea = document.getElementById("desc");
            textArea.value = metSample2p;
        }
    }
    else {
        if (language === 'cn') {
            var textArea = document.getElementById("desc");
            textArea.value = tensorSampler;
        }
        else if (language === 'en' && writeType === 'python') {
            var textArea = document.getElementById("desc");
            textArea.value = '';
        } else if (language === 'en' && writeType === 'yaml') {
            var textArea = document.getElementById("desc");
            textArea.value = tensorSampley;
        }
    }
}

function addNote() {
    var textArea = document.getElementById("desc");
    var cursorPosition = textArea.selectionStart;
    var textBeforeCursor = textArea.value.substring(0, cursorPosition);
    var textAfterCursor = textArea.value.substring(textArea.selectionEnd, textArea.value.length);
    var languageSelect = document.getElementById('language');
    var writeTypeSelect = document.getElementById("writetype");
    let language = languageSelect.value
    let writeType = writeTypeSelect.value
    if (language === 'cn') { var note = "\n" + "    " + ".. note::\n    "; }
    else if (language === 'en' && writeType === 'yaml') { var note = "\n" + "        " + "Note:\n    "; }
    else if (language === 'en' && writeType === 'python') { var note = "\n" + "    " + "Note:\n    "; }
    textArea.value = textBeforeCursor + note + textAfterCursor;
    textArea.selectionStart = textArea.selectionEnd = cursorPosition + note.length;
}

function addWarning() {
    var textArea = document.getElementById("desc");
    var cursorPosition = textArea.selectionStart;
    var textBeforeCursor = textArea.value.substring(0, cursorPosition);
    var textAfterCursor = textArea.value.substring(textArea.selectionEnd, textArea.value.length);
    var languageSelect = document.getElementById('language');
    var writeTypeSelect = document.getElementById("writetype");
    let language = languageSelect.value
    let writeType = writeTypeSelect.value
    if (language === 'cn') { var warning = "\n" + "    " + ".. warning::\n    "; }
    else if (language === 'en' && writeType === 'yaml') { var warning = "\n" + "        " + ".. warning::\n    "; }
    else if (language === 'en' && writeType === 'python') { var warning = "\n" + "    " + ".. warning::\n    "; }
    textArea.value = textBeforeCursor + warning + textAfterCursor;
    textArea.selectionStart = textArea.selectionEnd = cursorPosition + warning.length;
}

function addFormular() {
    var textArea = document.getElementById("desc");
    var cursorPosition = textArea.selectionStart;
    var textBeforeCursor = textArea.value.substring(0, cursorPosition);
    var textAfterCursor = textArea.value.substring(textArea.selectionEnd, textArea.value.length);
    var languageSelect = document.getElementById('language');
    var writeTypeSelect = document.getElementById("writetype");
    let language = languageSelect.value
    let writeType = writeTypeSelect.value
    if (language === 'cn') { var formular = "\n" + "    " + ".. math::\n    "; }
    else if (language === 'en' && writeType === 'yaml') { var formular = "\n" + "        " + ".. math::\n    "; }
    else if (language === 'en' && writeType === 'python') { var formular = "\n" + "    " + ".. math::\n    "; }
    textArea.value = textBeforeCursor + formular + textAfterCursor;
    textArea.selectionStart = textArea.selectionEnd = cursorPosition + formular.length;
}

function addCode() {
    var textArea = document.getElementById("desc");
    var cursorPosition = textArea.selectionStart;
    var textBeforeCursor = textArea.value.substring(0, cursorPosition);
    var textAfterCursor = textArea.value.substring(textArea.selectionEnd, textArea.value.length);
    var languageSelect = document.getElementById('language');
    var writeTypeSelect = document.getElementById("writetype");
    let language = languageSelect.value
    let writeType = writeTypeSelect.value
    if (language === 'cn') { var code = "\n" + "    " + ".. code-block::\n    "; }
    else if (language === 'en' && writeType === 'yaml') { var code = "\n" + "        " + ".. code-block::\n    "; }
    else if (language === 'en' && writeType === 'python') { var code = "\n" + "    " + ".. code-block::\n    "; }
    textArea.value = textBeforeCursor + code + textAfterCursor;
    textArea.selectionStart = textArea.selectionEnd = cursorPosition + code.length;
}

function addTable() {
    var textArea = document.getElementById("desc");
    var cursorPosition = textArea.selectionStart;
    var textBeforeCursor = textArea.value.substring(0, cursorPosition);
    var textAfterCursor = textArea.value.substring(textArea.selectionEnd, textArea.value.length);
    var languageSelect = document.getElementById('language');
    var writeTypeSelect = document.getElementById("writetype");
    let language = languageSelect.value
    let writeType = writeTypeSelect.value
    var tableEn = "\n+---------------+---------------+---------------+\n|    Title 1    |    Title 2    |    Title 3    |\n+===============+===============+===============+\n| XXX           | XXX1          | XXX11         |\n|               +---------------+---------------+\n|               | XXX2          | XXX22         |\n+---------------+---------------+---------------+\n| YYY           | YYY1          | YYY11         |\n|               +---------------+---------------+\n|               | YYY2          | YYY22         |\n+---------------+---------------+---------------+\n";
    var tableCn = "\n+---------------+---------------+---------------+\n| 第一列标题    | 第二列标题    | 第三列标题    |\n+===============+===============+===============+\n| XXX           | XXX1          | XXX11         |\n|               +---------------+---------------+\n|               | XXX2          | XXX22         |\n+---------------+---------------+---------------+\n| YYY           | YYY1          | YYY11         |\n|               +---------------+---------------+\n|               | YYY2          | YYY22         |\n+---------------+---------------+---------------+\n"
    var indentedTableCn = tableCn.replace(/^/gm, "    ");
    var indentedTableEny = tableEn.replace(/^/gm, "        ");
    var indentedTableEnp = tableEn.replace(/^/gm, "    ");
    if (language === 'cn') { var table = indentedTableCn; }
    else if (language === 'en' && writeType === 'yaml') { var table = indentedTableEny; }
    else if (language === 'en' && writeType === 'python') { var table = indentedTableEnp; }
    textArea.value = textBeforeCursor + table + textAfterCursor;
    textArea.selectionStart = textArea.selectionEnd = cursorPosition + table.length;
}

function addUnorderedList() {
    var textArea = document.getElementById("desc");
    var cursorPosition = textArea.selectionStart;
    var textBeforeCursor = textArea.value.substring(0, cursorPosition);
    var textAfterCursor = textArea.value.substring(textArea.selectionEnd, textArea.value.length);
    var languageSelect = document.getElementById('language');
    var writeTypeSelect = document.getElementById("writetype");
    let language = languageSelect.value
    let writeType = writeTypeSelect.value
    var underedList = "\n- \n- \n- \n";
    var indentedunderedList = underedList.replace(/^/gm, "        ");
    var indentedunderedListEny = underedList.replace(/^/gm, "            ");
    var indentedunderedListEnp = underedList.replace(/^/gm, "        ");
    if (language === 'cn') { var udList = indentedunderedList; }
    else if (language === 'en' && writeType === 'yaml') { var udList = indentedunderedListEny; }
    else if (language === 'en' && writeType === 'python') { var udList = indentedunderedListEnp; }
    textArea.value = textBeforeCursor + udList + textAfterCursor;
    textArea.selectionStart = textArea.selectionEnd = cursorPosition + udList.length;
}

function addInnerApi() {
    var textArea = document.getElementById("desc");
    var cursorPosition = textArea.selectionStart;
    var textBeforeCursor = textArea.value.substring(0, cursorPosition);
    var textAfterCursor = textArea.value.substring(textArea.selectionEnd, textArea.value.length);
    var innerName = " :class:`mindspore.xx.xxx` / :func:`mindspore.xx.xxx` / :math:`mindspore.xx.xxx` ";
    textArea.value = textBeforeCursor + innerName + textAfterCursor;
    textArea.selectionStart = textArea.selectionEnd = cursorPosition + innerName.length;
}

function addRaise() {
    var textArea = document.getElementById("desc");
    var cursorPosition = textArea.selectionStart;
    var textBeforeCursor = textArea.value.substring(0, cursorPosition);
    var textAfterCursor = textArea.value.substring(textArea.selectionEnd, textArea.value.length);
    var languageSelect = document.getElementById('language');
    var writeTypeSelect = document.getElementById("writetype");
    let language = languageSelect.value
    let writeType = writeTypeSelect.value
    var raiseCn = "        - **TypeError** – 异常描述。"
    var raiseEny = "            TypeError: description."
    var raiseEnp = "        TypeError: description."
    if (language === 'cn') { var raAdd = raiseCn; }
    else if (language === 'en' && writeType === 'yaml') { var raAdd = raiseEny; }
    else if (language === 'en' && writeType === 'python') { var raAdd = raiseEnp; }
    textArea.value = textBeforeCursor + raAdd + textAfterCursor;
    textArea.selectionStart = textArea.selectionEnd = cursorPosition + raAdd.length;

}

function getNewDivId(parent_id) {
    var parentDiv = document.getElementById(parent_id);
    var count = 0;
    for (var i = 0; i < parentDiv.childNodes.length; i++) {
        var child = parentDiv.childNodes[i];
        if (child.nodeType == Node.ELEMENT_NODE && child.tagName.toLowerCase() == "div") {
            count++;
        }
    }
    return parent_id + "_" + count.toString();
}

function addDiv(parent_id) {
    var id_next = getNewDivId(parent_id);
    var div = document.createElement("div");
    var select = document.createElement("select");
    var option1 = document.createElement("option");
    var option2 = document.createElement("option");
    var input1 = document.createElement("input");
    var input2 = document.createElement("input");
    var br = document.createElement("br");
    var textarea = document.createElement("textarea");
    var add = document.createElement("button");
    var sub = document.createElement("button");

    div.id = id_next;
    select.name = parent_id + "_type";
    option1.value = "int";
    option2.value = "str";
    option1.text = "int";
    option2.text = "str";
    select.appendChild(option1);
    select.appendChild(option2);

    input1.type = "text";
    input1.size = "20";
    input1.placeholder = parent_id == "return" ? "请填写返回参数名称（选填）" : "请填写参数名称";
    input1.name = parent_id + "_name";

    input2.type = "text";
    input2.size = "10";
    input2.placeholder = "默认值";
    input2.name = parent_id + "_default";

    textarea.rows = "2";
    textarea.cols = "60";
    textarea.placeholder = "请填写描述说明";
    textarea.name = parent_id + "_desc";

    add.textContent = "+";
    add.onclick = function () { addDiv(parent_id); };
    sub.textContent = "-";
    sub.onclick = function () { deleteDiv(parent_id, id_next) };

    div.appendChild(select);
    div.appendChild(input1);
    if (parent_id == "param" || parent_id == "keyword_param") {
        div.appendChild(input2);
    }
    div.appendChild(br);
    div.appendChild(textarea);
    div.appendChild(add);
    div.appendChild(sub);

    document.getElementById(parent_id).appendChild(div);
}

function deleteDiv(parent_id, child_id) {
    var parentDiv = document.getElementById(parent_id);
    var childDiv = document.getElementById(child_id);
    console.log("childNodes num: " + parentDiv.childNodes.length);
    var min = parent_id == "exception" ? 7 : 5;
    if (parentDiv.childNodes.length <= min) {
        for (var i = 0; i < childDiv.children.length; i++) {
            var granChild = childDiv.children[i];
            var index = child_id.lastIndexOf('_');
            if (granChild.name == child_id.slice(0, index) + "_name") {
                granChild.value = "";
            }
            if (granChild.name == child_id.slice(0, index) + "_default") {
                granChild.value = "";
            }
            if (granChild.name == child_id.slice(0, index) + "_desc") {
                granChild.value = "";
            }
        }
    } else {
        parentDiv.removeChild(childDiv, true);
    }
}

function addException(parent_id) {
    var id_next = getNewDivId(parent_id);
    var div = document.createElement("div");
    var select = document.createElement("select");
    var option1 = document.createElement("option");
    var option2 = document.createElement("option");
    var option3 = document.createElement("option");
    var option4 = document.createElement("option");
    var option5 = document.createElement("option");
    var option6 = document.createElement("option");
    var option7 = document.createElement("option");
    var input = document.createElement("input");
    var add = document.createElement("button");
    var sub = document.createElement("button");

    div.id = id_next;
    select.name = "exception_type";
    option1.value = "ValueError";
    option1.text = "ValueError";
    option2.value = "TypeError";
    option2.text = "TypeError";
    option3.value = "RuntimeError";
    option3.text = "RuntimeError";
    option4.value = "ImportError";
    option4.text = "ImportError";
    option5.value = "AssertionError";
    option5.text = "AssertionError";
    option6.value = "OSError";
    option6.text = "OSError";
    option7.value = "NotImplementedError";
    option7.text = "NotImplementedError";

    select.appendChild(option1);
    select.appendChild(option2);
    select.appendChild(option3);
    select.appendChild(option4);
    select.appendChild(option5);
    select.appendChild(option6);
    select.appendChild(option7);

    input.type = "text";
    input.size = "50";
    input.placeholder = "请填写异常描述";
    input.name = "exception_desc";

    add.textContent = "+";
    add.onclick = function () { addException(parent_id); };
    sub.textContent = "-";
    sub.onclick = function () { deleteDiv(parent_id, id_next) };

    div.appendChild(select);
    div.appendChild(input);
    div.appendChild(add);
    div.appendChild(sub);

    document.getElementById(parent_id).appendChild(div);
}

function getModuleContent(id) {
    var curText = "";
    if (id == "param") {
        curText = isLanguageCN ? "参数：" : "Args:";
    } else if (id == "keyword_param") {
        curText = isLanguageCN ? "关键字参数：" : "Keyword Args:";
    } else if (id == "input") {
        curText = isLanguageCN ? "输入：" : "Inputs:";
    } else if (id == "output") {
        curText = isLanguageCN ? "输出：" : "Outputs:";
    } else if (id == "return") {
        curText = isLanguageCN ? "返回：" : "Returns:";
    } else if (id == "exception") {
        curText = isLanguageCN ? "异常：" : "Raises:";
    } else if (id == "supported_platform") {
        curText = isLanguageCN ? "支持平台：" : "Supported Platforms:";
    } else {
        curText = isLanguageCN ? "样例：" : "Examples:";
    }

    if (isLanguageCN) {
        var paramContent = getContentWithWhiteSpace(id, EIGHT_WHITE_SPACE_TAB);
        document.getElementById("preview").value += paramContent == "" ? "" : ("\n" + curText.padStart(FOUR_WHITE_SPACE_TAB + curText.length, " ") + "\n" + paramContent);
    } else {
        var paramContent = getContentWithWhiteSpace(id, FOUR_WHITE_SPACE_TAB);
        // console.log(id + ":" + paramContent);
        document.getElementById("preview").value += paramContent == "" ? "" : ("\n" + curText.padStart(NO_TAB + curText.length, " ") + "\n" + paramContent);
    }
}

function preview() {
    // 获取第一个 textarea 的内容
    var content = document.getElementById('desc').value;
    // 将内容设置到第二个 textarea
    document.getElementById('desc2').value = content;
}

function getContentWithWhiteSpace(id, tab) {
    var content = id == "desc" ? document.getElementById(id).value : id == "supported_platform" ? getSupportedPlatforms() : id == "samples" ? getSamples() : getParamContent(id);

    if (content == "") {
        return "";
    }
    content = content.replace("\n\n\n", "\n\n");
    var lines = content.split("\n");
    var newLines = "";

    for (var i = 0; i < lines.length; i++) {
        newLines += lines[i].padStart(tab + lines[i].length, " ") + "\n";
    }
    return newLines;
}

function addParamDefinition() {
    var content = document.getElementById("preview");
    var lines = content.value.split("\n");
    var newLines = "";

    for (var i = 0; i < lines.length; i++) {
        newLines += lines[i].indexOf(".. py:") != -1 ? (lines[i] + paramsDefinition + "\n") : (i == lines.length - 1) ? lines[i] : (lines[i] + "\n");
    }
    content.value = newLines;
}

function getParamContent(module_name) {
    var parent = document.getElementById(module_name);
    var output = "";
    paramsDefinition = module_name == "param" ? "(" : module_name == "keyword_param" ? paramsDefinition == "" ? "(*, " : paramsDefinition.replace(")", ", *, ") : paramsDefinition; // 参数拼接至接口定义
    for (var i = 0; i < parent.children.length; i++) {
        var child = parent.children[i];
        if (child.id != null && child.id.startsWith(module_name)) {
            var type = "";
            var name = "";
            var desc = "";
            var defaults = "";
            var skip = false;
            for (var j = 0; j < child.children.length; j++) {
                skip = false;
                var grandChild = child.children[j];
                if (grandChild.name == module_name + "_desc" && grandChild.value == "") {
                    skip = true;
                    break;
                }
                if (module_name != "return" && grandChild.name == module_name + "_name" && grandChild.value == "") {
                    skip = true;
                    break;
                }
                if (grandChild.name == (module_name + "_type")) {
                    type = grandChild.name == (module_name + "_type") ? grandChild.value : "";
                }
                if (grandChild.name == (module_name + "_name")) {
                    name = grandChild.name == (module_name + "_name") ? grandChild.value : "";
                }
                if (grandChild.name == (module_name + "_desc")) {
                    desc = grandChild.name == (module_name + "_desc") ? grandChild.value : "";
                }
                if (grandChild.name == (module_name + "_default")) {
                    defaults = grandChild.name == (module_name + "_default") ? grandChild.value : "";
                }
            }
            if (skip) {
                continue;
            }
            if (isLanguageCN || module_name == "input" || module_name == "output") {
                paramsDefinition += defaults == "" ? (name + ", ") : (name + "=" + defaults + ", ");
                name = module_name == "exception" ? ("- **" + type + "**") : module_name == "return" ? "" : ("- **" + name + "** (");
                type = defaults == "" ? type : isLanguageCN ? (type + "，可选") : (type + ", optional");
                desc = module_name == "exception" ? (" - " + desc) : module_name == "return" ? (isLanguageCN ? ("，" + desc) : (", " + desc)) : (") - " + desc);
                desc = isLanguageCN ? (desc.slice(-1) == "。" ? desc : (desc + "。")) : (desc.slice(-1) == "." ? desc : (desc + ".")); // 如果最后没有句号，补上
                var descLine = desc.split("\n");
                var descIntent = "";
                for (var k = 0; k < descLine.length; k++) {
                    descIntent += (k == 0) ? (descLine[k]) : module_name == "return" ? ("\n" + descLine[k]) : ("\n" + (descLine[k].padStart(2 + descLine[k].length, " "))); // 参数描述换行缩进
                }
                defaults = defaults == "" ? "" : ("默认值： ``" + defaults + "`` 。");
                output += module_name == "exception" ? (name + desc + "\n") : (name + type + descIntent + defaults + "\n");
            } else {
                name = module_name == "exception" ? (type + ": ") : module_name == "return" ? "" : (name + " (");
                type = defaults == "" ? type : (type + ", optional")
                desc = module_name == "exception" ? desc : module_name == "return" ? (", " + desc) : ("): " + desc);
                desc = desc.slice(-1) == "." ? desc : (desc + "."); // 如果最后没有句号，补上
                var descLine = desc.split("\n");
                var descIntent = "";
                for (var k = 0; k < descLine.length; k++) {
                    descIntent += (k == 0) ? (descLine[k]) : module_name == "return" ? ("\n" + descLine[k]) : ("\n" + (descLine[k].padStart(4 + descLine[k].length, " "))); // 参数描述换行缩进
                }
                defaults = defaults == "" ? "" : (" Default: ``" + defaults + "`` .");
                output += module_name == "exception" ? (name + desc + "\n") : (name + type + descIntent + defaults + "\n");
            }
        }
    }
    var threshold = module_name == "param" ? 1 : module_name == "keyword_param" ? 4 : 0;
    paramsDefinition = paramsDefinition.length > threshold ? (paramsDefinition.slice(-5) === ", *, " ? (paramsDefinition.substring(0, paramsDefinition.length - 5) + ")") : (paramsDefinition.substring(0, paramsDefinition.length - 2) + ")")) : "";
    return output.lastIndexOf("\n") == output.length - 1 ? output.substring(0, output.lastIndexOf("\n")) : output;
}

/**
* 获取支持平台多选框中选中的项
*/
function getSupportedPlatforms() {
    var checkboxes = document.getElementsByTagName("input");
    var platforms = "";
    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i].checked) {
            platforms += "``" + checkboxes[i].value + "`` ";
        }
    }
    var result = platforms.substring(0, platforms.length - 1);
    return result;
}

/**
* 获取样例代码
*/
function getSamples() {
    var code = document.getElementById("code");
    var code_output = document.getElementById("code_output");
    var codeLines = code.value.split("\n");
    var new_code = "";
    for (var i = 0; i < codeLines.length; i++) {
        new_code += i < codeLines.length - 1 ? codeLines[i] + "\n" : (codeLines[codeLines.length - 1].length > 4 && codeLines[i].charAt(4) == ' ') ? codeLines[i].replace(">>> ", "... ") : codeLines[i];
    }
    return new_code.length <= 5 ? "" : code_output.value == "" ? (new_code.substring(0, new_code.length - 1) + code_output.value) : (new_code + "\n" + code_output.value);
}

function downloadDoc() {
    // 获取用户输入的 API 名称
    var apiName = document.getElementById('api_name').value.trim();

    // 检查用户是否输入了 API 名称
    if (apiName === '') {
        alert('请输入API名称');
        return;
    }

    var content = document.getElementById('desc2').value;

    // 创建一个 Blob 对象，内容类型为 text/plain
    var blob = new Blob([content], { type: 'text/plain' });

    // 创建一个链接元素
    var link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = apiName + '.rst'; // 使用用户输入的 API 名称作为文件名

    // 将链接元素添加到文档中
    document.body.appendChild(link);

    // 模拟点击链接进行下载
    link.click();

    // 移除链接元素
    document.body.removeChild(link);
}

function fixDoc() {
    var content = document.getElementById('desc2');
    var languageSelect = document.getElementById('language');
    var writeTypeSelect = document.getElementById("writetype");
    let language = languageSelect.value
    let writeType = writeTypeSelect.value
    if (language === 'cn') {
        var lines = content.value.split('\n');

        // 处理第一行和第二行的长度差异
        if (lines.length > 1) {
            var firstLine = lines[0].trim();
            var secondLine = lines[1].trim();
            var lengthDifference = firstLine.length - secondLine.length;
            if (lengthDifference > 0) {
                secondLine += '='.repeat(lengthDifference);
            }
            lines[1] = secondLine;
        }
        // 单次遍历处理所有逻辑
        for (let i = 0; i < lines.length; i++) {
            let line = lines[i];
            const leadingSpaces = line.match(/^ */)[0]; // 保留原有的缩进

            // 处理以 .. py: 开头并以 ) 结尾的行
            const classLineRegex = /(\.\.\s*py:)(.*?)(\)\s*)$/;
            const match = line.trim().match(classLineRegex);
            if (match) {
                const [fullMatch, start, middle, end] = match;
                const formattedMiddle = middle.replace(/,\s+/g, ', ').replace(/,([^,\s])/g, ', $1');
                line = leadingSpaces + start + formattedMiddle + end;
            }

            // 处理以 `` 开头并以 `` 结尾的字符串
            line = line.replace(/(`{3})(\s*)([^`]+?)(\s*)(`{3})/g, (match, p1, p2, p3, p4, p5) => {
                return `${leadingSpaces}${p1} ${p3.trim()} ${p5}`;
            });

            // 检查当前行是否以 .. 开头并包含 :: 
            if (line.trim().startsWith("..") && line.trim().includes("::")) {
                // 确保这一行的前一行是空行
                if (i > 0 && lines[i - 1].trim() !== '') {
                    // 如果前一行不是空行，则在它前面插入一个新的空行
                    lines.splice(i, 0, `${leadingSpaces}`); // 在当前行前插入空行，保留原有的缩进
                    i++; // 移动索引以跳过新插入的空行
                }
                // 确保前两行不为空行
                if (i >= 2 && lines[i - 2].trim() === '') {
                    // 如果前两行是空行，则删除一个空行
                    lines.splice(i - 1, 1);
                    i--;
                }
            }

            // 更新处理后的行
            lines[i] = line;
        }
    }
    content.value = lines.join('\n');
}
